package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.nursing.vo.ReservationCountAndTimeVo;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.ReservationMapper;
import com.zzyl.nursing.domain.Reservation;
import com.zzyl.nursing.service.IReservationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 预约信息Service业务层处理
 * 
 * @author gziqi
 * @date 2025-01-10
 */
@Service
public class ReservationServiceImpl extends ServiceImpl<ReservationMapper, Reservation> implements IReservationService
{
    @Autowired
    private ReservationMapper reservationMapper;

    /**
     * 查询预约信息
     * 
     * @param id 预约信息主键
     * @return 预约信息
     */
    @Override
    public Reservation selectReservationById(Long id)
    {
        return reservationMapper.selectById(id);
    }

    /**
     * 查询预约信息列表
     * 
     * @param reservation 预约信息
     * @return 预约信息
     */
    @Override
    public List<Reservation> selectReservationList(Reservation reservation)
    {
        return reservationMapper.selectReservationList(reservation);
    }


    /**
     * 新增预约信息
     * @param reservation
     * @return
     */
    @Override
    public int insertReservation(Reservation reservation)
    {
        Long userId = UserThreadLocal.getUserId();

        reservation.setStatus(0);

        reservation.setCreateBy(String.valueOf(userId));
        reservation.setUpdateBy(String.valueOf(userId));

        try {
            return save(reservation)?1:0;
        } catch (Exception e) {
            throw new RuntimeException("不可重复预约哦");
        }
    }

    /**
     * 修改预约信息
     * 
     * @param reservation 预约信息
     * @return 结果
     */
    @Override
    public int updateReservation(Reservation reservation)
    {
        return reservationMapper.updateById(reservation);
    }

    /**
     * 批量删除预约信息
     * 
     * @param ids 需要删除的预约信息主键
     * @return 结果
     */
    @Override
    public int deleteReservationByIds(Long[] ids)
    {
        return reservationMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除预约信息信息
     * 
     * @param id 预约信息主键
     * @return 结果
     */
    @Override
    public void deleteReservationById(Long id)
    {
        //根据预约信息id判断预约记录是否存在
        Reservation reservation = reservationMapper.selectById(id);
        if(ObjectUtils.isEmpty(reservation)){
            throw new BaseException("预约记录不存在");
        }
        Long userId = UserThreadLocal.getUserId();
        //调用查询剩余次数的方法
        if (getCancelledReservationCount(userId) > 3) {
            throw new BaseException("取消预约次数已达限");
        }

        reservation.setStatus(2);
        reservation.setUpdateBy(String.valueOf(userId));
            reservationMapper.updateById(reservation);

    }

    /**
     * 查询取消预约次数
     *
     * @param userId
     * @return
     */
    @Override
    public int getCancelledReservationCount(Long userId) {
        long time = System.currentTimeMillis();
        LocalDateTime ldt = LocalDateTimeUtil.of(time);
        //今天的开始时间
        LocalDateTime startTime = ldt.toLocalDate().atStartOfDay();
        //今天的结束时间
        LocalDateTime endTime = startTime.plusDays(1);
        if(userId==null){
            throw new BaseException("预约人不存在");
        }
        LambdaQueryWrapper<Reservation> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Reservation::getUpdateBy,userId).between(Reservation::getUpdateTime,startTime,endTime)
                .eq(Reservation::getStatus,2);
        Long count = count(lambdaQueryWrapper);

        return Math.toIntExact(count);

    }

    /**
     * 查询某个时间段剩余的预约次数
     *
     * @param time
     * @return ReservationCountAndTimeVo
     */
    @Override
    public List<ReservationCountAndTimeVo> selectCountByTime(long time) {
        //获取这个时间段对应的时间日期
        LocalDateTime localDateTime = LocalDateTimeUtil.of(time);
        //获取当天的开始时间
        LocalDateTime  startTime = localDateTime.toLocalDate().atStartOfDay();
        //获取当天的结束时间
        LocalDateTime endTime = startTime.plusDays(1);

        return reservationMapper.selectCountByTime(startTime,endTime);
    }

    /**
     * 小程序端分页查询
     *
     * @param pageNum
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public TableDataInfo<Reservation> numberPage(Integer pageNum, Integer pageSize, Integer status) {
        Long userId = UserThreadLocal.getUserId();
        if(ObjectUtils.isEmpty(userId)){
            throw new BaseException("请先登录");
        }
        LambdaQueryWrapper<Reservation> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Reservation::getCreateBy,userId)
                .eq(ObjectUtils.isNotEmpty(status),Reservation::getStatus,status)
                .orderByDesc(Reservation::getCreateTime);
        Page<Reservation> page = new Page<>(pageNum,pageSize);
        page = page(page, lambdaQueryWrapper);

        return createTableDataInfo(page);
    }

    private TableDataInfo<Reservation> createTableDataInfo(Page<Reservation> page) {
        TableDataInfo<Reservation> tableDataInfo = new TableDataInfo<>();
        tableDataInfo.setCode(200);
        tableDataInfo.setMsg("查询成功");
        tableDataInfo.setRows(page.getRecords());
        tableDataInfo.setTotal(page.getTotal());
        return tableDataInfo;
    }

    /**
     * 根据时间定时更新预约信息
     */
    @Override
    public void updateReservationByTime() {
        List<Reservation> reservations = reservationMapper.selectList(Wrappers.<Reservation>lambdaQuery()
                .eq(Reservation::getStatus, 0)
                .lt(Reservation::getTime, LocalDateTime.now().minusMinutes(30)));
        //循环遍历这些过期的预约信息
        reservations.forEach(reservation -> {
            reservation.setStatus(3);
        });
        updateBatchById(reservations);
    }
}
